package com.example.seabedmusic.views;

import android.content.Intent;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.seabedmusic.R;
import com.example.seabedmusic.contract.MusicContract;
import com.example.seabedmusic.entity.HotSong;
import com.example.seabedmusic.entity.Playlist;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.presenter.MusicPresenter;
import com.example.seabedmusic.utils.LocalMusicManager;
import com.example.seabedmusic.utils.PlaylistManager;
import com.example.seabedmusic.utils.RecentPlayManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HotMusicPlayerActivity extends AppCompatActivity implements MusicContract.IMusicView {

    private ImageButton btnBack, btnPlayPause, btnPrevious, btnNext, btnFavorite, btnAddToPlaylist, btnDownload;
    private TextView tvSongName, tvLyrics, tvCurrentTime, tvTotalTime;
    private SeekBar seekBar;
    private ScrollView lyricsScrollView;

    private MediaPlayer mediaPlayer;
    private Handler handler;
    private boolean isPlaying = false;
    private boolean isPrepared = false;

    // MediaPlayer状态常量
    private static final int STATE_IDLE = 0;
    private static final int STATE_INITIALIZED = 1;
    private static final int STATE_PREPARING = 2;
    private static final int STATE_PREPARED = 3;
    private static final int STATE_STARTED = 4;
    private static final int STATE_PAUSED = 5;
    private static final int STATE_STOPPED = 6;
    private static final int STATE_ERROR = -1;

    private int currentState = STATE_IDLE;

    private List<HotSong> hotSongList = new ArrayList<>();
    private int currentSongIndex = 0;
    private MusicContract.IMusicPresenter mPresenter;
    private PlaylistManager playlistManager;
    private RecentPlayManager recentPlayManager;
    private LocalMusicManager localMusicManager; // 新增：本地音乐管理器
    private OkHttpClient httpClient;

    // 歌词相关变量
    private List<LyricLine> lyricLines = new ArrayList<>();
    private Handler lyricsHandler;
    private Runnable lyricsScrollRunnable;
    private boolean isLyricsLoaded = false;
    private int currentLyricIndex = -1;
    private boolean isLyricsScrollingEnabled = true;
    private boolean isLyricsTextSet = false;
    private SpannableStringBuilder lyricsBuilder;

    // 歌词行数据类
    private static class LyricLine {
        long time; // 时间戳（毫秒）
        String text; // 歌词文本

        LyricLine(long time, String text) {
            this.time = time;
            this.text = text;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        // 隐藏ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        // 使用主线程的 Looper 创建 Handler
        handler = new Handler(Looper.getMainLooper());
        lyricsHandler = new Handler(Looper.getMainLooper());

        // 初始化HTTP客户端
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .followRedirects(true)
                .followSslRedirects(true)
                .build();

        // 初始化Presenter
        mPresenter = new MusicPresenter(this, this);
        // 初始化歌单管理器
        playlistManager = PlaylistManager.getInstance();
        // 初始化最近播放管理器
        recentPlayManager = RecentPlayManager.getInstance(this);
        // 初始化本地音乐管理器
        localMusicManager = LocalMusicManager.getInstance(this);

        initViews();
        setupMediaPlayer();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btnBack);
        btnPlayPause = findViewById(R.id.btnPlayPause);
        btnPrevious = findViewById(R.id.btnPrevious);
        btnNext = findViewById(R.id.btnNext);
        btnFavorite = findViewById(R.id.btnFavorite);
        btnAddToPlaylist = findViewById(R.id.btnAddToPlaylist);
        btnDownload = findViewById(R.id.btnDownload); // 下载按钮

        tvSongName = findViewById(R.id.tvSongName);
        tvLyrics = findViewById(R.id.tvLyrics);
        tvCurrentTime = findViewById(R.id.tvCurrentTime);
        tvTotalTime = findViewById(R.id.tvTotalTime);
        seekBar = findViewById(R.id.seekBar);
        lyricsScrollView = findViewById(R.id.lyricsScrollView);

        // 初始禁用播放按钮
        btnPlayPause.setEnabled(false);

        tvLyrics.setMovementMethod(new android.text.method.ScrollingMovementMethod());
        tvLyrics.setVerticalScrollBarEnabled(false);

        // 设置文本变化监听，确保布局完成
        tvLyrics.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {
                // 布局变化时重新计算滚动位置
                if (currentLyricIndex >= 0 && isPlaying) {
                    lyricsScrollView.postDelayed(() -> {
                        smoothScrollToLyricLine(currentLyricIndex);
                    }, 100);
                }
            }
        });

        setListeners();
    }

    /**
     * 设置媒体播放器 - 从Intent获取热歌数据
     */
    private void setupMediaPlayer() {
        try {
            // 从Intent获取传递的热歌数据
            String songTitle = getIntent().getStringExtra("song_title");
            String songArtist = getIntent().getStringExtra("song_artist");
            String songCover = getIntent().getStringExtra("song_cover");
            String songAlbum = getIntent().getStringExtra("song_album");
            String songHash = getIntent().getStringExtra("song_hash");
            int songRank = getIntent().getIntExtra("song_rank", 0);
            int currentPosition = getIntent().getIntExtra("current_position", 0);

            android.util.Log.d("HotMusicPlayerActivity", "接收到热歌数据: " +
                    "title=" + songTitle +
                    ", artist=" + songArtist +
                    ", rank=" + songRank +
                    ", hash=" + songHash +
                    ", position=" + currentPosition);

            // 获取传递的热歌列表
            ArrayList<HotSong> receivedList = getIntent().getParcelableArrayListExtra("hot_song_list");
            if (receivedList != null && !receivedList.isEmpty()) {
                hotSongList.clear();
                hotSongList.addAll(receivedList);
                currentSongIndex = currentPosition;
                android.util.Log.d("HotMusicPlayerActivity", "接收到热歌列表，共 " + hotSongList.size() + " 首歌曲");
            }

            if (songTitle != null && !songTitle.isEmpty()) {
                // 如果列表中没有当前歌曲，创建并添加
                if (hotSongList.isEmpty()) {
                    HotSong receivedSong = new HotSong();
                    receivedSong.setName(songTitle);
                    receivedSong.setAuthor(songArtist != null ? songArtist : "未知歌手");
                    receivedSong.setCover(songCover);
                    receivedSong.setAlbum(songAlbum != null ? songAlbum : "热门专辑");
                    receivedSong.setHash(songHash != null ? songHash : "");
                    receivedSong.setRank(songRank);
                    receivedSong.setId(String.valueOf(System.currentTimeMillis()));

                    hotSongList.clear();
                    hotSongList.add(receivedSong);
                    currentSongIndex = 0;
                }

                // 更新UI
                updateSongInfo();

                // 使用网易云音乐API搜索并播放
                getNeteasePlayUrl(songTitle, songArtist != null ? songArtist : "");
            } else {
                android.util.Log.e("HotMusicPlayerActivity", "未接收到有效的歌曲数据");
                Toast.makeText(this, "未找到歌曲数据", Toast.LENGTH_SHORT).show();
                finish();
            }

        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayerActivity", "播放器初始化失败", e);
            Toast.makeText(this, "播放器初始化失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * URL编码
     */
    private String encode(String text) {
        try {
            return URLEncoder.encode(text, "UTF-8");
        } catch (Exception e) {
            return text;
        }
    }

    /**
     * 使用网易云音乐API获取播放URL
     */
    private void getNeteasePlayUrl(String songName, String artist) {
        showLoading();

        // 构建搜索关键词
        String keyword = songName;
        if (artist != null && !artist.isEmpty()) {
            keyword = songName + " " + artist;
        }

        // 网易云音乐搜索API
        String searchApi = "https://music.163.com/api/search/get/web?s=" + encode(keyword) + "&type=1&limit=1";

        android.util.Log.d("HotMusicPlayer", "使用网易云API搜索: " + searchApi);

        Request request = new Request.Builder()
                .url(searchApi)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Referer", "https://music.163.com/")
                .addHeader("Origin", "https://music.163.com")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                android.util.Log.e("HotMusicPlayer", "网易云搜索失败: " + e.getMessage());
                runOnUiThread(() -> {
                    hideLoading();
                    Toast.makeText(HotMusicPlayerActivity.this, "搜索歌曲失败", Toast.LENGTH_SHORT).show();
                    btnPlayPause.setEnabled(true);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        android.util.Log.d("HotMusicPlayer", "网易云API响应: " + responseBody);

                        // 解析网易云API响应
                        String playUrl = parseNeteaseResponse(responseBody);

                        if (playUrl != null && !playUrl.isEmpty()) {
                            // 获取真实的音频URL（处理重定向）
                            getRealAudioUrl(playUrl);
                        } else {
                            runOnUiThread(() -> {
                                hideLoading();
                                Toast.makeText(HotMusicPlayerActivity.this, "未找到可播放的歌曲", Toast.LENGTH_SHORT).show();
                                btnPlayPause.setEnabled(true);
                            });
                        }
                    } catch (Exception e) {
                        android.util.Log.e("HotMusicPlayer", "解析网易云响应失败: " + e.getMessage());
                        runOnUiThread(() -> {
                            hideLoading();
                            Toast.makeText(HotMusicPlayerActivity.this, "解析歌曲信息失败", Toast.LENGTH_SHORT).show();
                            btnPlayPause.setEnabled(true);
                        });
                    }
                } else {
                    android.util.Log.e("HotMusicPlayer", "网易云API响应失败: " + response.code());
                    runOnUiThread(() -> {
                        hideLoading();
                        Toast.makeText(HotMusicPlayerActivity.this, "搜索失败，状态码: " + response.code(), Toast.LENGTH_SHORT).show();
                        btnPlayPause.setEnabled(true);
                    });
                }
            }
        });
    }

    /**
     * 解析网易云音乐API响应
     */
    private String parseNeteaseResponse(String responseBody) {
        try {
            JSONObject json = new JSONObject(responseBody);

            // 检查响应状态
            if (json.getInt("code") != 200) {
                android.util.Log.e("HotMusicPlayer", "网易云API返回错误: " + json.getInt("code"));
                return null;
            }

            // 解析搜索结果
            JSONObject result = json.getJSONObject("result");
            JSONArray songs = result.getJSONArray("songs");

            if (songs.length() > 0) {
                JSONObject song = songs.getJSONObject(0);
                String songId = song.getString("id");
                String songName = song.getString("name");

                // 获取歌手信息
                JSONArray artists = song.getJSONArray("artists");
                StringBuilder artistNames = new StringBuilder();
                for (int i = 0; i < artists.length(); i++) {
                    JSONObject artist = artists.getJSONObject(i);
                    if (artistNames.length() > 0) {
                        artistNames.append("/");
                    }
                    artistNames.append(artist.getString("name"));
                }

                android.util.Log.d("HotMusicPlayer", "找到歌曲: " + songName + " - " + artistNames + " (ID: " + songId + ")");

                // 生成网易云音乐外链播放URL
                String playUrl = "https://music.163.com/song/media/outer/url?id=" + songId + ".mp3";

                // 更新UI中的歌曲信息（使用网易云返回的准确信息）
                runOnUiThread(() -> {
                    if (!hotSongList.isEmpty()) {
                        HotSong currentSong = hotSongList.get(currentSongIndex);
                        currentSong.setName(songName);
                        currentSong.setAuthor(artistNames.toString());
                        updateSongInfo();

                        // 获取歌词
                        getLyrics(songId);
                    }
                });

                return playUrl;
            } else {
                android.util.Log.e("HotMusicPlayer", "未找到匹配的歌曲");
                return null;
            }

        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayer", "解析网易云响应异常: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取真实的音频URL（处理网易云外链重定向）
     */
    private void getRealAudioUrl(String playUrl) {
        android.util.Log.d("HotMusicPlayer", "获取真实音频URL: " + playUrl);

        // 创建一个支持重定向的客户端
        OkHttpClient redirectClient = new OkHttpClient.Builder()
                .connectTimeout(8, TimeUnit.SECONDS)
                .readTimeout(8, TimeUnit.SECONDS)
                .followRedirects(true) // 启用自动重定向
                .followSslRedirects(true)
                .build();

        Request request = new Request.Builder()
                .url(playUrl)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .addHeader("Accept", "audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5")
                .addHeader("Referer", "https://music.163.com/")
                .addHeader("Range", "bytes=0-") // 添加Range头，避免下载整个文件
                .build();

        // 先测试URL是否可达
        redirectClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                android.util.Log.e("HotMusicPlayer", "测试URL失败: " + e.getMessage());
                runOnUiThread(() -> {
                    // URL不可达，尝试直接使用原始URL
                    android.util.Log.d("HotMusicPlayer", "URL测试失败，直接尝试播放: " + playUrl);
                    prepareMediaPlayerWithUrl(playUrl);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 如果响应成功，说明URL可达，使用最终URL
                if (response.isSuccessful() || response.isRedirect()) {
                    String finalUrl = response.request().url().toString();
                    android.util.Log.d("HotMusicPlayer", "最终播放URL: " + finalUrl);
                    runOnUiThread(() -> {
                        prepareMediaPlayerWithUrl(finalUrl);
                    });
                } else {
                    // 响应失败，尝试原始URL
                    runOnUiThread(() -> {
                        android.util.Log.d("HotMusicPlayer", "响应失败，使用原始URL: " + playUrl);
                        prepareMediaPlayerWithUrl(playUrl);
                    });
                }
            }
        });
    }

    /**
     * 使用URL准备媒体播放器
     */
    private void prepareMediaPlayerWithUrl(String playUrl) {
        try {
            // 先释放之前的 MediaPlayer
            safeReleaseMediaPlayer();

            mediaPlayer = new MediaPlayer();
            currentState = STATE_IDLE;
            isPrepared = false;

            android.util.Log.d("HotMusicPlayerActivity", "设置播放URL: " + playUrl);

            // 设置超时处理
            handler.postDelayed(prepareTimeoutRunnable, 15000); // 15秒超时

            // 设置数据源
            mediaPlayer.setDataSource(playUrl);
            currentState = STATE_INITIALIZED;

            // 设置音频属性
            mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build());

            currentState = STATE_PREPARING;
            mediaPlayer.prepareAsync();

            mediaPlayer.setOnPreparedListener(mp -> {
                handler.removeCallbacks(prepareTimeoutRunnable);
                runOnUiThread(() -> {
                    currentState = STATE_PREPARED;
                    isPrepared = true;
                    int duration = mp.getDuration();
                    seekBar.setMax(duration);
                    tvTotalTime.setText(formatTime(duration));
                    btnPlayPause.setEnabled(true);
                    hideLoading();

                    android.util.Log.d("HotMusicPlayerActivity", "媒体准备完成，时长: " + duration);

                    // 记录到最近播放
                    addToRecentPlay();

                    // 自动开始播放
                    togglePlayPause();
                });
            });

            mediaPlayer.setOnCompletionListener(mp -> {
                runOnUiThread(() -> {
                    currentState = STATE_STOPPED;
                    isPlaying = false;
                    btnPlayPause.setSelected(false);
                    android.util.Log.d("HotMusicPlayerActivity", "播放完成");

                    // 自动播放下一首
                    handler.postDelayed(() -> {
                        playNextSong();
                    }, 1000); // 1秒后自动播放下一首
                });
            });

            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                handler.removeCallbacks(prepareTimeoutRunnable);
                runOnUiThread(() -> {
                    currentState = STATE_ERROR;
                    isPrepared = false;
                    hideLoading();
                    android.util.Log.e("MediaPlayer", "播放错误: what=" + what + ", extra=" + extra);

                    // 尝试其他播放方案
                    if (!hotSongList.isEmpty()) {
                        HotSong currentSong = hotSongList.get(currentSongIndex);
                        Toast.makeText(HotMusicPlayerActivity.this,
                                "播放失败: " + getErrorDescription(what, extra), Toast.LENGTH_SHORT).show();

                        // 尝试使用备用API
                        tryAlternativePlayMethod(currentSong.getName(), currentSong.getAuthor());
                    }
                    btnPlayPause.setEnabled(true);
                });
                return true;
            });

            // 添加缓冲监听
            mediaPlayer.setOnInfoListener((mp, what, extra) -> {
                switch (what) {
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        android.util.Log.d("MediaPlayer", "开始缓冲");
                        break;
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                        android.util.Log.d("MediaPlayer", "缓冲结束");
                        break;
                }
                return false;
            });

        } catch (Exception e) {
            handler.removeCallbacks(prepareTimeoutRunnable);
            runOnUiThread(() -> {
                hideLoading();
                android.util.Log.e("HotMusicPlayerActivity", "播放器初始化失败", e);
                Toast.makeText(HotMusicPlayerActivity.this,
                        "播放器初始化失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                btnPlayPause.setEnabled(true);
            });
        }
    }

    /**
     * 新增：添加到最近播放
     */
    private void addToRecentPlay() {
        if (!hotSongList.isEmpty() && currentSongIndex >= 0 && currentSongIndex < hotSongList.size()) {
            HotSong currentHotSong = hotSongList.get(currentSongIndex);
            Song currentSong = convertToSong(currentHotSong);

            // 记录到最近播放
            if (recentPlayManager != null) {
                recentPlayManager.addToRecent(currentSong);
                android.util.Log.d("HotMusicPlayerActivity", "歌曲已添加到最近播放: " + currentSong.getTitle());
            }
        }
    }

    /**
     * 准备超时的Runnable
     */
    private Runnable prepareTimeoutRunnable = new Runnable() {
        @Override
        public void run() {
            if (currentState == STATE_PREPARING) {
                runOnUiThread(() -> {
                    android.util.Log.e("MediaPlayer", "媒体准备超时");
                    safeReleaseMediaPlayer();
                    hideLoading();
                    Toast.makeText(HotMusicPlayerActivity.this, "媒体准备超时，请检查网络连接", Toast.LENGTH_SHORT).show();
                    btnPlayPause.setEnabled(true);

                    // 尝试备用方案
                    if (!hotSongList.isEmpty()) {
                        HotSong currentSong = hotSongList.get(currentSongIndex);
                        tryAlternativePlayMethod(currentSong.getName(), currentSong.getAuthor());
                    }
                });
            }
        }
    };

    /**
     * 尝试备用播放方法
     */
    private void tryAlternativePlayMethod(String songName, String artist) {
        showLoading();
        Toast.makeText(this, "尝试备用播放方案...", Toast.LENGTH_SHORT).show();

        // 备用方案1: 使用其他API
        String alternativeApi = "https://api.qqsuu.cn/api/dm-music?name=" + encode(songName + " " + artist);

        android.util.Log.d("HotMusicPlayer", "尝试备用API: " + alternativeApi);

        Request request = new Request.Builder()
                .url(alternativeApi)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    hideLoading();
                    Toast.makeText(HotMusicPlayerActivity.this, "备用方案也失败了", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        // 简单解析响应，假设返回的是直接URL
                        if (responseBody.startsWith("http")) {
                            runOnUiThread(() -> {
                                android.util.Log.d("HotMusicPlayer", "备用API获取到URL: " + responseBody);
                                prepareMediaPlayerWithUrl(responseBody);
                            });
                            return;
                        }
                    } catch (Exception e) {
                        android.util.Log.e("HotMusicPlayer", "解析备用API失败", e);
                    }
                }
                runOnUiThread(() -> {
                    hideLoading();
                    Toast.makeText(HotMusicPlayerActivity.this, "无法播放此歌曲", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    /**
     * 获取错误描述
     */
    private String getErrorDescription(int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                return "未知错误";
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                return "服务器连接失败";
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                return "不支持的音频格式";
            case MediaPlayer.MEDIA_ERROR_IO:
                return "网络连接错误";
            case MediaPlayer.MEDIA_ERROR_MALFORMED:
                return "音频文件损坏";
            case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                return "不支持的音频格式";
            case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                return "连接超时";
            default:
                return "错误代码: " + what + "," + extra;
        }
    }

    private void togglePlayPause() {
        if (mediaPlayer == null) {
            android.util.Log.w("MediaPlayer", "MediaPlayer 为空");
            return;
        }

        try {
            if (isPlaying) {
                // 暂停播放
                mediaPlayer.pause();
                currentState = STATE_PAUSED;
                isPlaying = false;
                btnPlayPause.setSelected(false);
                handler.removeCallbacks(updateTimeTask);

                // 暂停歌词滚动
                if (lyricsScrollRunnable != null) {
                    lyricsHandler.removeCallbacks(lyricsScrollRunnable);
                }
                android.util.Log.d("MediaPlayer", "暂停播放");
            } else {
                // 继续播放或重新开始播放
                if (currentState == STATE_PAUSED && isPrepared) {
                    // 从暂停状态恢复播放
                    mediaPlayer.start();
                    currentState = STATE_STARTED;
                    isPlaying = true;
                    btnPlayPause.setSelected(true);

                    // 恢复更新进度条
                    handler.post(updateTimeTask);

                    // 恢复歌词滚动
                    if (isLyricsLoaded) {
                        startLyricsScroll();
                    }
                    android.util.Log.d("MediaPlayer", "从暂停恢复播放");
                } else if (currentState == STATE_STOPPED && isPrepared) {
                    // 播放完成后重新开始
                    mediaPlayer.seekTo(0);
                    mediaPlayer.start();
                    currentState = STATE_STARTED;
                    isPlaying = true;
                    btnPlayPause.setSelected(true);

                    // 开始更新进度条
                    handler.post(updateTimeTask);

                    // 开始歌词滚动
                    if (isLyricsLoaded) {
                        startLyricsScroll();
                    }
                    android.util.Log.d("MediaPlayer", "重新开始播放");
                } else if (currentState == STATE_PREPARED) {
                    // 初次播放
                    mediaPlayer.start();
                    currentState = STATE_STARTED;
                    isPlaying = true;
                    btnPlayPause.setSelected(true);

                    // 开始更新进度条
                    handler.post(updateTimeTask);

                    // 开始歌词滚动
                    if (isLyricsLoaded) {
                        startLyricsScroll();
                    }
                    android.util.Log.d("MediaPlayer", "开始播放");
                } else {
                    android.util.Log.w("MediaPlayer", "无法播放，当前状态: " + currentState + ", 准备状态: " + isPrepared);
                    Toast.makeText(this, "播放器未准备好", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (IllegalStateException e) {
            android.util.Log.e("MediaPlayer", "播放状态异常: " + e.getMessage());
            Toast.makeText(this, "播放状态异常", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 播放上一首歌曲
     */
    private void playPreviousSong() {
        if (hotSongList.isEmpty()) {
            showToast("没有可播放的歌曲");
            return;
        }

        // 计算上一首的索引（循环播放）
        currentSongIndex--;
        if (currentSongIndex < 0) {
            currentSongIndex = hotSongList.size() - 1; // 循环到最后一首
        }

        playSongAtIndex(currentSongIndex);
    }

    /**
     * 播放下一首歌曲
     */
    private void playNextSong() {
        if (hotSongList.isEmpty()) {
            showToast("没有可播放的歌曲");
            return;
        }

        // 计算下一首的索引（循环播放）
        currentSongIndex++;
        if (currentSongIndex >= hotSongList.size()) {
            currentSongIndex = 0; // 循环到第一首
        }

        playSongAtIndex(currentSongIndex);
    }

    /**
     * 获取当前歌曲
     */
    private HotSong getCurrentSong() {
        if (!hotSongList.isEmpty() && currentSongIndex >= 0 && currentSongIndex < hotSongList.size()) {
            return hotSongList.get(currentSongIndex);
        }
        return null;
    }

    private void updateSongInfo() {
        if (!hotSongList.isEmpty() && currentSongIndex >= 0 && currentSongIndex < hotSongList.size()) {
            HotSong currentSong = hotSongList.get(currentSongIndex);
            tvSongName.setText(currentSong.getName());

            // 显示歌手信息
            String artistInfo = currentSong.getAuthor();
            if (artistInfo != null && !artistInfo.isEmpty()) {
                // 这里不再设置歌词，因为歌词会单独加载
            } else {
                tvLyrics.setText("未知歌手");
            }

            // 修复：安全地检查喜欢状态
            try {
                Song convertedSong = convertToSong(currentSong);
                // 确保歌曲ID不为null
                if (convertedSong.getId() == null) {
                    convertedSong.setId(String.valueOf(System.currentTimeMillis()));
                }
                boolean isFavorite = playlistManager.isFavorite(convertedSong);
                btnFavorite.setSelected(isFavorite);
            } catch (Exception e) {
                android.util.Log.e("HotMusicPlayer", "检查喜欢状态失败: " + e.getMessage());
                btnFavorite.setSelected(false);
            }

            // 更新下载按钮状态
            updateDownloadButtonState();

            // 重置进度条
            seekBar.setProgress(0);
            tvCurrentTime.setText("0:00");
            tvTotalTime.setText("0:00");

            // 显示当前播放位置（可选）
            android.util.Log.d("HotMusicPlayer", "当前播放: " + (currentSongIndex + 1) + "/" + hotSongList.size());
        }
    }

    /**
     * 将HotSong转换为Song对象 - 修复版本
     */
    private Song convertToSong(HotSong hotSong) {
        Song song = new Song();
        // 确保ID不为null
        String id = hotSong.getId();
        if (id == null || id.isEmpty()) {
            id = String.valueOf(System.currentTimeMillis());
        }
        song.setId(id);

        song.setTitle(hotSong.getName() != null ? hotSong.getName() : "未知歌曲");
        song.setArtist(hotSong.getAuthor() != null ? hotSong.getAuthor() : "未知歌手");
        song.setCover(hotSong.getCover());
        song.setAlbum(hotSong.getAlbum() != null ? hotSong.getAlbum() : "热门专辑");

        // 确保URL不为null
        String url = "https://music.163.com/song/media/outer/url?id=" +
                (hotSong.getHash() != null ? hotSong.getHash() : "");
        song.setUrl(url);

        return song;
    }

    /**
     * 切换喜欢状态
     */
    private void toggleFavorite() {
        if (hotSongList.isEmpty()) return;

        HotSong currentHotSong = getCurrentSong();
        if (currentHotSong == null) return;

        try {
            Song currentSong = convertToSong(currentHotSong);
            // 确保歌曲ID不为null
            if (currentSong.getId() == null) {
                currentSong.setId(String.valueOf(System.currentTimeMillis()));
            }

            boolean newState = !playlistManager.isFavorite(currentSong);

            if (newState) {
                // 添加到"我喜欢的"
                boolean success = playlistManager.addToFavorite(currentSong);
                if (success) {
                    btnFavorite.setSelected(true);
                    Toast.makeText(this, "已添加到我喜欢", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "已在我喜欢中", Toast.LENGTH_SHORT).show();
                }
            } else {
                // 从"我喜欢的"移除
                boolean success = playlistManager.removeFromFavorite(currentSong);
                if (success) {
                    btnFavorite.setSelected(false);
                    Toast.makeText(this, "已从我喜欢移除", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayer", "切换喜欢状态失败: " + e.getMessage());
            Toast.makeText(this, "操作失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 下载当前歌曲到本地音乐
     */
    private void downloadCurrentSong() {
        if (hotSongList.isEmpty()) {
            showToast("暂无歌曲可下载");
            return;
        }

        HotSong currentHotSong = getCurrentSong();
        if (currentHotSong == null) {
            showToast("无法获取当前歌曲");
            return;
        }

        try {
            Song currentSong = convertToSong(currentHotSong);
            // 确保歌曲ID不为null
            if (currentSong.getId() == null) {
                currentSong.setId(String.valueOf(System.currentTimeMillis()));
            }

            boolean success = localMusicManager.addSongToLocal(currentSong);
            if (success) {
                showToast("已下载到本地音乐");
                // 更新下载按钮状态
                updateDownloadButtonState();
            } else {
                showToast("歌曲已在本地音乐中");
            }
        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayer", "下载歌曲失败: " + e.getMessage());
            Toast.makeText(this, "下载失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新下载按钮状态
     */
    private void updateDownloadButtonState() {
        if (hotSongList.isEmpty()) return;

        HotSong currentHotSong = getCurrentSong();
        if (currentHotSong != null) {
            try {
                Song currentSong = convertToSong(currentHotSong);
                // 确保歌曲ID不为null
                if (currentSong.getId() == null) {
                    currentSong.setId(String.valueOf(System.currentTimeMillis()));
                }
                boolean isInLocal = localMusicManager.isSongInLocal(currentSong);
                btnDownload.setSelected(isInLocal);
            } catch (Exception e) {
                android.util.Log.e("HotMusicPlayer", "更新下载按钮状态失败: " + e.getMessage());
                btnDownload.setSelected(false);
            }
        }
    }

    private void updateSeekBar() {
        if (isPrepared && isPlaying) {
            // 确保只有一个更新任务在运行
            handler.removeCallbacks(updateTimeTask);
            handler.post(updateTimeTask);
        }
    }

    private Runnable updateTimeTask = new Runnable() {
        public void run() {
            if (mediaPlayer != null && isPrepared && isPlaying) {
                try {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    seekBar.setProgress(currentPosition);
                    tvCurrentTime.setText(formatTime(currentPosition));

                    // 继续循环更新，每100毫秒更新一次以获得更流畅的体验
                    handler.postDelayed(this, 100);
                } catch (IllegalStateException e) {
                    android.util.Log.e("MediaPlayer", "获取当前位置异常: " + e.getMessage());
                    handler.removeCallbacks(this);
                    return;
                }
            }
        }
    };

    private void setListeners() {
        btnBack.setOnClickListener(v -> finish());

        btnPlayPause.setOnClickListener(v -> togglePlayPause());

        btnPrevious.setOnClickListener(v -> playPreviousSong());

        btnNext.setOnClickListener(v -> playNextSong());

        btnFavorite.setOnClickListener(v -> toggleFavorite());

        btnAddToPlaylist.setOnClickListener(v -> showPlaylistSelectionDialog());

        // 新增：下载按钮点击监听
        btnDownload.setOnClickListener(v -> downloadCurrentSong());

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    tvCurrentTime.setText(formatTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeCallbacks(updateTimeTask);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null && isPrepared) {
                    try {
                        mediaPlayer.seekTo(seekBar.getProgress());
                        if (isPlaying) {
                            updateSeekBar();
                        }
                    } catch (IllegalStateException e) {
                        android.util.Log.e("MediaPlayer", "seekTo 状态异常: " + e.getMessage());
                    }
                }
            }
        });
    }

    /**
     * 显示歌单选择对话框
     */
    private void showPlaylistSelectionDialog() {
        if (hotSongList.isEmpty()) {
            showToast("暂无歌曲可添加");
            return;
        }

        HotSong currentHotSong = getCurrentSong();
        if (currentHotSong == null) {
            showToast("无法获取当前歌曲");
            return;
        }

        try {
            Song currentSong = convertToSong(currentHotSong);
            // 确保歌曲ID不为null
            if (currentSong.getId() == null) {
                currentSong.setId(String.valueOf(System.currentTimeMillis()));
            }

            // 获取所有歌单（排除"我喜欢的"歌单）
            List<Playlist> allPlaylists = playlistManager.getAllPlaylists();
            List<Playlist> userPlaylists = new ArrayList<>();

            for (Playlist playlist : allPlaylists) {
                // 排除"我喜欢的"歌单
                if (!"我喜欢的".equals(playlist.getName())) {
                    userPlaylists.add(playlist);
                }
            }

            if (userPlaylists.isEmpty()) {
                // 如果没有用户创建的歌单，提示创建
                showCreatePlaylistDialog(currentSong);
                return;
            }

            // 创建歌单名称数组
            String[] playlistNames = new String[userPlaylists.size()];
            for (int i = 0; i < userPlaylists.size(); i++) {
                playlistNames[i] = userPlaylists.get(i).getName() + " (" + userPlaylists.get(i).getSongCount() + "首)";
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("添加到歌单");
            builder.setItems(playlistNames, (dialog, which) -> {
                Playlist selectedPlaylist = userPlaylists.get(which);
                addSongToPlaylist(currentSong, selectedPlaylist);
            });

            // 添加"新建歌单"选项
            builder.setNeutralButton("新建歌单", (dialog, which) -> {
                showCreatePlaylistDialog(currentSong);
            });

            builder.setNegativeButton("取消", null);
            builder.show();
        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayer", "显示歌单选择对话框失败: " + e.getMessage());
            Toast.makeText(this, "加载歌单失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示创建新歌单对话框
     */
    private void showCreatePlaylistDialog(Song song) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("新建歌单");

        final EditText input = new EditText(this);
        input.setHint("输入歌单名称");
        input.setSingleLine(true);
        builder.setView(input);

        builder.setPositiveButton("创建", (dialog, which) -> {
            String playlistName = input.getText().toString().trim();
            if (!playlistName.isEmpty()) {
                // 创建新歌单并添加歌曲
                Playlist newPlaylist = playlistManager.createPlaylist(playlistName, "新建歌单");
                if (newPlaylist != null) {
                    addSongToPlaylist(song, newPlaylist);
                    showToast("歌单创建成功，歌曲已添加");
                } else {
                    showToast("歌单创建失败");
                }
            } else {
                showToast("请输入歌单名称");
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 添加歌曲到指定歌单
     */
    private void addSongToPlaylist(Song song, Playlist playlist) {
        try {
            boolean success = playlistManager.addSongToPlaylist(playlist.getId(), song);
            if (success) {
                showToast("已添加到歌单: " + playlist.getName());
                sendPlaylistUpdateBroadcast();
            } else {
                showToast("歌曲已在歌单中");
            }
        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayer", "添加歌曲到歌单失败: " + e.getMessage());
            Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 发送歌单更新广播
     */
    private void sendPlaylistUpdateBroadcast() {
        LocalBroadcastManager.getInstance(this)
                .sendBroadcast(new Intent("PLAYLIST_UPDATED"));
    }

    /**
     * 安全的释放MediaPlayer
     */
    private void safeReleaseMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                // 先移除所有监听器，避免回调
                mediaPlayer.setOnPreparedListener(null);
                mediaPlayer.setOnCompletionListener(null);
                mediaPlayer.setOnErrorListener(null);
                mediaPlayer.setOnInfoListener(null);
                mediaPlayer.setOnSeekCompleteListener(null);

                handler.removeCallbacks(updateTimeTask);
                handler.removeCallbacks(prepareTimeoutRunnable);

                if (currentState >= STATE_PREPARED) {
                    try {
                        mediaPlayer.stop();
                    } catch (IllegalStateException e) {
                        android.util.Log.w("MediaPlayer", "停止播放时状态异常: " + e.getMessage());
                    }
                }

                mediaPlayer.release();
            } catch (Exception e) {
                android.util.Log.e("MediaPlayer", "释放MediaPlayer异常: " + e.getMessage());
            } finally {
                mediaPlayer = null;
                isPrepared = false;
                isPlaying = false;
                currentState = STATE_IDLE;
            }
        }
    }

    /**
     * 释放所有资源
     */
    private void releaseAllResources() {
        // 1. 释放 MediaPlayer
        safeReleaseMediaPlayer();

        // 2. 移除所有 Handler 回调
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }

        // 3. 移除歌词相关的 Handler 回调
        if (lyricsHandler != null) {
            lyricsHandler.removeCallbacksAndMessages(null);
        }

        // 4. 取消所有网络请求
        if (httpClient != null) {
            try {
                httpClient.dispatcher().cancelAll();
            } catch (Exception e) {
                android.util.Log.e("ResourceCleanup", "取消网络请求失败: " + e.getMessage());
            }
        }

        // 5. 清理静态引用
        lyricLines.clear();
        lyricsBuilder = null;

        // 6. 清理 Presenter
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    private String formatTime(int milliseconds) {
        long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) -
                TimeUnit.MINUTES.toSeconds(minutes);
        return String.format("%d:%02d", minutes, seconds);
    }

    /**
     * 显示Toast消息
     */
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    // =============== MusicContract.IMusicView 接口实现 ===============

    @Override
    public void showSongs(List<Song> songs) {
        if (songs != null && !songs.isEmpty()) {
            showToast("切换到新歌曲: " + songs.get(0).getTitle());
        }
    }

    @Override
    public void showRecent(List<Song> songs) {
        // 播放页面不需要显示最近播放
    }

    @Override
    public void showLoading() {
        btnPrevious.setEnabled(false);
        btnNext.setEnabled(false);
        btnPlayPause.setEnabled(false);
    }

    @Override
    public void hideLoading() {
        btnPrevious.setEnabled(true);
        btnNext.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseAllResources();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 暂停歌词滚动以节省资源
        isLyricsScrollingEnabled = false;

        if (isPlaying && mediaPlayer != null && isPrepared) {
            try {
                mediaPlayer.pause();
                currentState = STATE_PAUSED;
                isPlaying = false;
                btnPlayPause.setSelected(false);
                handler.removeCallbacks(updateTimeTask);
            } catch (IllegalStateException e) {
                android.util.Log.e("MediaPlayer", "暂停时异常: " + e.getMessage());
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 恢复歌词滚动
        isLyricsScrollingEnabled = true;

        if (mediaPlayer != null && isPrepared && !isPlaying) {
            updateSeekBar();
        }

        // 如果正在播放，重新开始歌词滚动
        if (isPlaying && isLyricsLoaded) {
            startLyricsScroll();
        }
    }

    // =============== 歌词相关方法 ===============

    /**
     * 获取歌词
     */
    private void getLyrics(String songId) {
        // 检查 Activity 状态
        if (isFinishing() || isDestroyed()) {
            return;
        }

        String lyricsApi = "https://music.163.com/api/song/lyric?id=" + songId + "&lv=1&kv=1&tv=1";

        android.util.Log.d("HotMusicPlayer", "获取歌词: " + lyricsApi);

        Request request = new Request.Builder()
                .url(lyricsApi)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .addHeader("Referer", "https://music.163.com/")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                android.util.Log.e("HotMusicPlayer", "获取歌词失败: " + e.getMessage());
                runOnUiThread(() -> {
                    tvLyrics.setText("歌词加载失败");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        android.util.Log.d("HotMusicPlayer", "歌词API响应: " + responseBody);

                        // 使用新的歌词解析方法
                        parseLyricsWithTime(responseBody);

                    } catch (Exception e) {
                        android.util.Log.e("HotMusicPlayer", "解析歌词失败: " + e.getMessage());
                        runOnUiThread(() -> {
                            tvLyrics.setText("歌词解析失败");
                        });
                    }
                } else {
                    android.util.Log.e("HotMusicPlayer", "歌词API响应失败: " + response.code());
                    runOnUiThread(() -> {
                        tvLyrics.setText("歌词获取失败");
                    });
                }
            }
        });
    }

    /**
     * 解析歌词响应 - 支持时间轴
     */
    private void parseLyricsWithTime(String responseBody) {
        try {
            JSONObject json = new JSONObject(responseBody);

            if (json.getInt("code") != 200) {
                android.util.Log.e("HotMusicPlayer", "歌词API返回错误: " + json.getInt("code"));
                runOnUiThread(() -> {
                    tvLyrics.setText("歌词加载失败");
                });
                return;
            }

            lyricLines.clear();

            // 解析歌词数据
            JSONObject lrc = json.optJSONObject("lrc");
            if (lrc != null) {
                String lyrics = lrc.optString("lyric", "");
                if (!lyrics.isEmpty()) {
                    parseLyricText(lyrics);
                    isLyricsLoaded = true;
                    startLyricsScroll();
                    return;
                }
            }

            // 如果没有歌词，尝试获取翻译
            JSONObject tlyric = json.optJSONObject("tlyric");
            if (tlyric != null) {
                String translatedLyrics = tlyric.optString("lyric", "");
                if (!translatedLyrics.isEmpty()) {
                    parseLyricText(translatedLyrics);
                    isLyricsLoaded = true;
                    startLyricsScroll();
                    return;
                }
            }

            // 没有找到歌词
            runOnUiThread(() -> {
                tvLyrics.setText("暂无歌词");
            });

        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayer", "解析歌词响应异常: " + e.getMessage());
            runOnUiThread(() -> {
                tvLyrics.setText("歌词解析失败");
            });
        }
    }

    /**
     * 解析带时间轴的歌词文本
     */
    private void parseLyricText(String lyricsText) {
        try {
            String[] lines = lyricsText.split("\n");

            for (String line : lines) {
                // 匹配时间轴格式 [00:00.00]
                Pattern pattern = Pattern.compile("\\[(\\d+):(\\d+)\\.(\\d+)\\]");
                Matcher matcher = pattern.matcher(line);

                while (matcher.find()) {
                    int minutes = Integer.parseInt(matcher.group(1));
                    int seconds = Integer.parseInt(matcher.group(2));
                    int milliseconds = Integer.parseInt(matcher.group(3));

                    // 计算总毫秒数
                    long time = minutes * 60 * 1000 + seconds * 1000 + milliseconds;

                    // 获取歌词文本（去除时间轴）
                    String text = line.substring(matcher.end()).trim();

                    if (!text.isEmpty()) {
                        lyricLines.add(new LyricLine(time, text));
                    }
                }
            }

            // 按时间排序
            lyricLines.sort((o1, o2) -> Long.compare(o1.time, o2.time));

            android.util.Log.d("HotMusicPlayer", "解析到 " + lyricLines.size() + " 行歌词");

            // 显示所有歌词
            displayAllLyrics();

        } catch (Exception e) {
            android.util.Log.e("HotMusicPlayer", "解析歌词文本异常: " + e.getMessage());
            runOnUiThread(() -> {
                tvLyrics.setText("歌词格式错误");
            });
        }
    }

    /**
     * 显示所有歌词
     */
    private void displayAllLyrics() {
        runOnUiThread(() -> {
            if (lyricLines.isEmpty()) {
                tvLyrics.setText("🎵 暂无歌词 🎵");
                tvLyrics.setTextColor(0xFF666666);
                return;
            }

            // 构建歌词文本
            lyricsBuilder = new SpannableStringBuilder();

            for (int i = 0; i < lyricLines.size(); i++) {
                LyricLine line = lyricLines.get(i);
                String text = line.text + "\n";
                SpannableString span = new SpannableString(text);

                // 初始状态所有歌词都是普通样式
                span.setSpan(new android.text.style.ForegroundColorSpan(0xFFE0E0E0),
                        0, text.length(), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                span.setSpan(new android.text.style.RelativeSizeSpan(1.0f),
                        0, text.length(), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                lyricsBuilder.append(span);
            }

            tvLyrics.setText(lyricsBuilder);
            tvLyrics.setTextColor(0xFFE0E0E0);
            isLyricsTextSet = true;

            // 重置滚动位置
            lyricsScrollView.post(() -> {
                lyricsScrollView.scrollTo(0, 0);
                currentLyricIndex = -1;
            });
        });
    }

    /**
     * 开始歌词滚动
     */
    private void startLyricsScroll() {
        if (lyricsScrollRunnable != null) {
            lyricsHandler.removeCallbacks(lyricsScrollRunnable);
        }

        lyricsScrollRunnable = new Runnable() {
            @Override
            public void run() {
                if (isLyricsLoaded && mediaPlayer != null && isPlaying && isLyricsScrollingEnabled) {
                    try {
                        int currentPosition = mediaPlayer.getCurrentPosition();
                        highlightCurrentLyric(currentPosition);

                        // 优化更新频率
                        lyricsHandler.postDelayed(this, 100);
                    } catch (Exception e) {
                        android.util.Log.e("HotMusicPlayer", "歌词滚动异常: " + e.getMessage());
                    }
                }
            }
        };

        lyricsHandler.post(lyricsScrollRunnable);
    }

    /**
     * 高亮显示当前歌词 - 改进版本
     */
    private void highlightCurrentLyric(int currentPosition) {
        if (lyricLines.isEmpty()) return;

        // 找到当前时间对应的歌词行
        int newCurrentLineIndex = findCurrentLyricIndex(currentPosition);

        // 只有当歌词行发生变化时才更新UI
        if (newCurrentLineIndex != currentLyricIndex) {
            currentLyricIndex = newCurrentLineIndex;

            // 立即更新高亮和滚动
            updateHighlightOnly(currentLyricIndex);

            // 添加小延迟确保视图更新完成后再滚动
            lyricsHandler.postDelayed(() -> {
                smoothScrollToLyricLine(currentLyricIndex);
            }, 100);
        }
    }

    /**
     * 优化歌词时间轴匹配算法
     */
    private int findCurrentLyricIndex(int currentPosition) {
        if (lyricLines.isEmpty()) return -1;

        // 使用二分查找提高效率
        int low = 0;
        int high = lyricLines.size() - 1;

        while (low <= high) {
            int mid = (low + high) / 2;
            long midTime = lyricLines.get(mid).time;

            if (midTime <= currentPosition) {
                if (mid == lyricLines.size() - 1 || lyricLines.get(mid + 1).time > currentPosition) {
                    return mid;
                }
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return -1;
    }

    /**
     * 只更新高亮状态而不重新设置整个文本
     */
    private void updateHighlightOnly(int lineIndex) {
        if (lyricsBuilder == null || lineIndex < 0 || lineIndex >= lyricLines.size()) {
            return;
        }

        runOnUiThread(() -> {
            try {
                // 重新构建整个歌词文本，简化逻辑
                SpannableStringBuilder newBuilder = new SpannableStringBuilder();

                for (int i = 0; i < lyricLines.size(); i++) {
                    LyricLine line = lyricLines.get(i);
                    String text = line.text + "\n";
                    SpannableString span = new SpannableString(text);

                    if (i == lineIndex) {
                        // 当前行：高亮样式
                        span.setSpan(new android.text.style.ForegroundColorSpan(0xFF1DB954),
                                0, text.length(), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        span.setSpan(new android.text.style.RelativeSizeSpan(1.3f),
                                0, text.length(), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        span.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD),
                                0, text.length(), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else {
                        // 其他行：根据距离设置不同透明度
                        int distance = Math.abs(i - lineIndex);
                        int alpha;
                        if (distance == 1) alpha = 200;
                        else if (distance == 2) alpha = 150;
                        else if (distance == 3) alpha = 120;
                        else alpha = 100;

                        span.setSpan(new android.text.style.ForegroundColorSpan((alpha << 24) | 0xE0E0E0),
                                0, text.length(), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        span.setSpan(new android.text.style.RelativeSizeSpan(1.0f),
                                0, text.length(), android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }

                    newBuilder.append(span);
                }

                lyricsBuilder = newBuilder;
                tvLyrics.setText(lyricsBuilder);

            } catch (Exception e) {
                android.util.Log.e("LyricsHighlight", "高亮更新失败: " + e.getMessage());
            }
        });
    }

    /**
     * 改进的平滑滚动到指定歌词行
     */
    private void smoothScrollToLyricLine(int lineIndex) {
        if (lineIndex < 0 || lineIndex >= lyricLines.size()) return;

        runOnUiThread(() -> {
            // 延迟执行以确保视图已完成布局
            lyricsScrollView.post(() -> {
                try {
                    // 计算滚动位置
                    int targetScrollY = calculateExactScrollPosition(lineIndex);

                    // 获取当前滚动位置
                    int currentScrollY = lyricsScrollView.getScrollY();

                    // 如果目标位置与当前位置相差不大，不滚动
                    if (Math.abs(targetScrollY - currentScrollY) < 100) {
                        android.util.Log.d("LyricsScroll", "滚动距离过小，跳过滚动");
                        return;
                    }

                    lyricsScrollView.smoothScrollTo(0, targetScrollY);

                    // 添加滚动完成检查
                    lyricsScrollView.postDelayed(() -> {
                        checkScrollResult(lineIndex, targetScrollY);
                    }, 300);

                } catch (Exception e) {
                    android.util.Log.e("LyricsScroll", "滚动歌词异常: " + e.getMessage());
                    // 备用方案：使用简单计算
                    try {
                        int targetScrollY = calculateSimpleScrollPosition(lineIndex);
                        lyricsScrollView.scrollTo(0, targetScrollY);
                    } catch (Exception ex) {
                        android.util.Log.e("LyricsScroll", "备用滚动方案也失败: " + ex.getMessage());
                    }
                }
            });
        });
    }

    /**
     * 计算精确的滚动位置 - 基于实际测量
     */
    private int calculateExactScrollPosition(int lineIndex) {
        try {
            // 获取ScrollView的可视高度
            int scrollViewHeight = lyricsScrollView.getHeight();
            if (scrollViewHeight == 0) {
                return calculateSimpleScrollPosition(lineIndex);
            }

            // 计算实际行高
            int lineHeight = calculateActualLineHeight();

            // 计算目标行的顶部位置（考虑XML中的顶部填充）
            int topPadding = 400; // XML中顶部View的高度200dp ≈ 400px
            int targetLineTop = lineIndex * lineHeight + topPadding;

            // 计算目标行的中心位置
            int targetLineCenter = targetLineTop + lineHeight / 2;

            // 目标滚动位置：让目标行中心显示在ScrollView中心
            int targetScrollY = targetLineCenter - (scrollViewHeight / 2);

            // 确保不超出范围
            int totalContentHeight = lyricLines.size() * lineHeight + topPadding * 2;
            int maxScrollY = Math.max(0, totalContentHeight - scrollViewHeight);
            targetScrollY = Math.max(0, Math.min(targetScrollY, maxScrollY));

            android.util.Log.d("LyricsScroll",
                    "精确计算 - 行: " + lineIndex +
                            ", 行高: " + lineHeight +
                            ", 目标行顶部: " + targetLineTop +
                            ", 目标行中心: " + targetLineCenter +
                            ", ScrollView高度: " + scrollViewHeight +
                            ", 目标Y: " + targetScrollY +
                            ", 最大Y: " + maxScrollY);

            return targetScrollY;

        } catch (Exception e) {
            android.util.Log.e("LyricsScroll", "精确计算失败: " + e.getMessage());
            return calculateSimpleScrollPosition(lineIndex);
        }
    }

    /**
     * 计算实际行高
     */
    private int calculateActualLineHeight() {
        try {
            // 基于XML布局参数计算实际行高
            // textSize="18sp" + lineSpacingExtra="20dp" + 额外边距
            float textSizePx = tvLyrics.getTextSize(); // 18sp ≈ 36px
            float lineSpacingPx = tvLyrics.getLineSpacingExtra(); // 20dp ≈ 40px
            float density = getResources().getDisplayMetrics().density;

            // 实际每行高度 = 文字高度 + 行间距 + 段落间距
            int lineHeight = (int) (textSizePx + lineSpacingPx + 20 * density);

            android.util.Log.d("LyricsScroll", "计算行高 - 文字大小: " + textSizePx +
                    ", 行间距: " + lineSpacingPx + ", 密度: " + density + ", 结果: " + lineHeight);

            return Math.max(lineHeight, 120); // 最小120px

        } catch (Exception e) {
            android.util.Log.e("LyricsScroll", "计算行高失败: " + e.getMessage());
            return 150; // 默认行高
        }
    }

    /**
     * 简单可靠的滚动位置计算
     */
    private int calculateSimpleScrollPosition(int lineIndex) {
        try {
            int scrollViewHeight = lyricsScrollView.getHeight();
            if (scrollViewHeight == 0) scrollViewHeight = 1000;

            // 固定行高（根据实际情况调整）
            int lineHeight = 160;

            // 顶部填充高度（XML中200dp的View）
            int topPadding = 400;

            // 目标位置：让目标行显示在ScrollView的上半部分（1/3位置）
            int targetScrollY = (lineIndex * lineHeight + topPadding) - (scrollViewHeight / 3);

            // 确保不超出范围
            int totalContentHeight = lyricLines.size() * lineHeight + topPadding * 2;
            int maxScrollY = Math.max(0, totalContentHeight - scrollViewHeight);
            targetScrollY = Math.max(0, Math.min(targetScrollY, maxScrollY));

            android.util.Log.d("LyricsScroll", "简单计算 - 行: " + lineIndex +
                    ", 目标Y: " + targetScrollY + ", 最大Y: " + maxScrollY);

            return targetScrollY;

        } catch (Exception e) {
            android.util.Log.e("LyricsScroll", "简单计算失败: " + e.getMessage());
            return lineIndex * 160;
        }
    }

    /**
     * 检查滚动结果
     */
    private void checkScrollResult(int expectedLineIndex, int originalScrollY) {
        try {
            int currentScrollY = lyricsScrollView.getScrollY();
            int scrollViewHeight = lyricsScrollView.getHeight();

            // 计算当前可视区域
            int visibleTop = currentScrollY;
            int visibleBottom = currentScrollY + scrollViewHeight;
            int visibleCenter = currentScrollY + scrollViewHeight / 2;

            // 估算目标行应该在的位置范围
            int lineHeight = calculateActualLineHeight();
            int topPadding = 400;
            int expectedLineTop = expectedLineIndex * lineHeight + topPadding;
            int expectedLineBottom = expectedLineTop + lineHeight;
            int expectedLineCenter = expectedLineTop + lineHeight / 2;

            android.util.Log.d("LyricsScroll",
                    "滚动检查 - 当前Y: " + currentScrollY +
                            ", 可视区域: " + visibleTop + "-" + visibleBottom +
                            ", 目标行位置: " + expectedLineTop + "-" + expectedLineBottom +
                            ", 目标行中心: " + expectedLineCenter +
                            ", 可视中心: " + visibleCenter);

            // 检查目标行是否在可视区域内
            boolean isVisible = (expectedLineTop >= visibleTop && expectedLineBottom <= visibleBottom);
            boolean isCentered = Math.abs(expectedLineCenter - visibleCenter) < scrollViewHeight / 4;

            if (!isVisible || !isCentered) {
                android.util.Log.w("LyricsScroll",
                        "滚动未达到预期，重新调整 - 可视: " + isVisible + ", 居中: " + isCentered);

                // 重新滚动到更准确的位置
                int adjustedScrollY = expectedLineTop - (scrollViewHeight / 3);
                lyricsScrollView.smoothScrollTo(0, Math.max(0, adjustedScrollY));
            } else {
                android.util.Log.d("LyricsScroll", "滚动成功，目标行在可视区域内且居中");
            }

        } catch (Exception e) {
            android.util.Log.e("LyricsScroll", "滚动检查失败: " + e.getMessage());
        }
    }

    /**
     * 在播放新歌曲时重置歌词状态
     */
    private void playSongAtIndex(int index) {
        if (index < 0 || index >= hotSongList.size()) {
            showToast("歌曲索引无效");
            return;
        }

        currentSongIndex = index;
        HotSong song = hotSongList.get(currentSongIndex);

        // 重置歌词状态
        isLyricsLoaded = false;
        lyricLines.clear();
        currentLyricIndex = -1;
        isLyricsTextSet = false;
        lyricsBuilder = null;
        tvLyrics.setText("🎵 歌词加载中... 🎵");

        // 停止歌词滚动
        if (lyricsScrollRunnable != null) {
            lyricsHandler.removeCallbacks(lyricsScrollRunnable);
        }

        // 更新UI
        updateSongInfo();

        // 显示加载状态
        showLoading();

        // 使用网易云音乐API搜索并播放
        getNeteasePlayUrl(song.getName(), song.getAuthor());

        android.util.Log.d("HotMusicPlayer", "切换到歌曲: " + song.getName() + " - " + song.getAuthor());
    }
}